package com.ah.ues;

import com.ah.ues.runner.DingTalkStreamRegister;
import com.ah.ues.utils.GsonUtil;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/registerCallback")
public class DingTalkCallbackController {
    private static final Logger log = LoggerFactory.getLogger(DingTalkCallbackController.class);

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "ok";
    }

    @PostMapping("/test")
    public String hell2o(@RequestParam String clientId, @RequestParam String clientSecret) throws Exception {
        DingTalkStreamRegister.dingTalkRegister(clientId, clientSecret);
        return "ok";
    }

    @PostMapping("/test2")
    public String hell2o2() throws Exception {
        DingTalkStreamRegister.stop();
        return "ok";
    }

    @RequestMapping(value = "/dingTalk", method = RequestMethod.GET)
    public String dingTalk(@RequestParam(value = "code", required = false) String code, HttpServletResponse response) throws Exception {
        // https://open.dingtalk.com/document/orgapp/scan-qr-code-to-log-on-to-third-party-websites
        String json = null;
        try {
            System.out.println("code:" + code);
            json = dingTalkUserOld(code, "dingfib3ysek9jxtlqix", "etfgt0f0cV-tt_CgAyRbzztp81MPABWYrBuCt_XMHUMxmn67XdQ39OUEz38a_lnc");
            System.out.println("json:" + json);
            Map<String, Object> map = GsonUtil.toMap(json);
            String unionId = (String) map.get("unionId");
        } catch (Exception e) {
            log.error("登记异常：", e);
            response.sendRedirect("/error.html?error=" + e.getMessage());
            return e.getMessage();
        }
        return json;
    }

    public String dingTalkUser(String code, String key, String sec) {
        //获取userToken
        DingTalkApiClient client = new DingTalkApiClient(key, sec);
        String userToken = client.getOAuth2AccessTokenWithRefresh(code);
        // 获取用户信息
        return client.getUniqIdByUserToken(userToken);
    }

    public String dingTalkUserOld(String code, String key, String sec) throws Exception {
//        DingTalkApiClient client = new DingTalkApiClient(key, sec);
//        return client.getuserinfo_bycode(code);
        throw new RuntimeException("aaaa");
    }

}